<?php
namespace common\bonus;
use common\bonus\Validata;
use common\models\BaseModel;
use common\models\GroupDetail;
use common\models\TradeModel;
use common\models\Balance;
use common\models\BalanceLog;
use common\utils\CommonFun;
use common\models\Member;
use common\bonus\StaticRelease;
use common\models\StaticInstance;
### 加速奖励

class SpeedBonus extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'trade_speed_bonus';
    }
	public static $conf = [];

	public static function bonusAction($params)
	{

		self::$conf = TradeModel::getSpeedBonusConf('SpeedBonus', $params['model_id']);
		if(!self::$conf) return ['state'=>false,'msg'=>'参数配置有误'];


		if(!$params['uper']) return true;
		$curConf = self::$conf[0];  //获取一个配置

		$st = mktime(0,0,0,date('m'),date('d'),date('Y'));


		foreach($params['uper'] as $k => $member)
		{
		     $state = Member::getOne(['member_id'=>$member],'state');
            if ($state==0){
                continue;
            }
			if($k == 0) continue;

			if($k > count(self::$conf)) return true;
			$rate = self::getRate($member, $curConf, $k,$params['category']);

			if($rate <=0 ) continue;
			$money = round($params['money']*$rate/100,2);

			## 封顶限制
			$profit = BalanceLog::find()->where(['member_id' => $member['member_id'], 'balance_type' => 4, 'log_type' => 1])->andWhere(['>=', 'create_time', $st])->sum('balance');
			$staticTotal = StaticInstance::find()->where(['member_id' => $member['member_id']])->sum('in_num');
			/*今日收益必须有 且 用户必须有 合约收益 才去查询收益封顶*/
			if ($profit && $staticTotal) {
                if ($profit >= $staticTotal)  continue;
            }

			if($curConf['bonus_type'] == 1)
			{
				## 加速奖励到账本
				self::bonus($member,$money,$curConf,$params);
			}

			if($curConf['bonus_type'] == 2)
			{
				## 直接奖励
				$assignType = json_decode($curConf['assign_type'], 1);

				foreach($assignType as $btype=>$rate)
				{
					$balance = round($money * $rate / 100 , 2);

					//加入到账本
					$res = Balance::addBalance($member['member_id'], $btype, $balance, 17, $params['source_id'], $params['desc']);
					if(!$res['state']){
						$str = '加速奖励 member:'.json_encode($member).' data:'.json_encode($params)."\r\n conf:".json_encode(self::$conf).'msg:'.$res['msg'];
						CommonFun::writeLog($str,'bonus');
					}
				}				
			}
		}

		return ['state'=>true,'msg'=>'ok'];;
	}


	protected static function bonus($member,$money,$conf,$params)
	{
		$where = ['member_id'=>$member['member_id'],'status'=>'1'];

		$instances = StaticInstance::find()->where($where)->andWhere(['>','remain_num',0])->asarray()->all();
		if(!$instances) return true;

		//减少静态
		$remainBonus = $money;
		foreach($instances as $instance)
		{
			if($remainBonus<=0) return true;
			$maxBonus = min($remainBonus,$instance['remain_num']);
			$maxBonus = max($maxBonus,0);  
			$data = array();
			$data['remain_num'] = $instance['remain_num'] - $maxBonus;
			$data['was_num'] = $instance['was_num'] + $maxBonus;
			$data['update_time'] = time();
			if($data['remain_num']<=0) $data['status'] = '2';
			if(StaticInstance::updateAll($data,['id'=>$instance['id']])){
				$remainBonus -= $maxBonus;
			}
		}

		if($remainBonus==$money) return true;
		if($remainBonus>0) $money = $money - $remainBonus;


		## 帐本分配方式
		$assignType = json_decode($conf['assign_type'],1);
		foreach($assignType as $btype=>$rate)
		{
			$balance = round($money * $rate / 100 , 2);
			//加入到账本
			$res = Balance::addBalance($member['member_id'],$btype,$balance,9,$params['source_id'],$params['desc']);
			if(!$res['state']) {
				$str = '加速奖励 member:'.json_encode($member).' data:'.json_encode($params)."\r\n conf:".json_encode($conf).'msg:'.$res['msg'];
				CommonFun::writeLog($str,'bonus');
			}
		}
		return true;
	}


	protected static function getRate($member,$conf,$level,$category)
	{
		$conditionArr = explode(',',$conf['model_condition']);
		$ruleData = array();
        $is_instance = StaticInstance::getOne(['member_id' => $member['member_id'],'status'=>1]);
        if (!$is_instance){
        return 0;
        }
	
		//验证等级
		if(in_array('grade',$conditionArr))
		{
			$ruleData['context']['grade'] = $member['grade'];
		}

		//验证直推人数
		if(in_array('child_num',$conditionArr))
		{
			$childNum = Member::find()->where(['invite_id'=>$member['member_id']])->andWhere(['>','grade',0])->count();
			$ruleData['context']['child_num'] = $childNum;
		}

		## 是否参与了拼团
		if(in_array('pintuan', $conditionArr)) 
		{
			$ruleData['context']['pintuan'] = 0;
            $where =" member_id REGEXP '^".$member['member_id'].",|,".$member['member_id'].",|,".$member['member_id']."$'";
            /*区别脚本任务 和其他*/
             if ($category!=1) {
                $st    = date("Y-m-d");
                if($re = GroupDetail::find()->where($where)->andwhere(['=','group_time',$st])->one()){
                    $ruleData['context']['pintuan'] = 1;
                }else
                {
                    $ruleData['context']['pintuan'] = 0;
                }
            }
		}

        $ruleData['context']['invest_money'] = 0;

		if ($level) {
            /*找到所有的直推用户*/
            $userArr = Member::getAll(['invite_id' => $member['member_id']], 'member_id');
            if ($userArr) {
                /*验证上级合约价格*/
                $users = array_column($userArr, 'member_id');
                $ruleData['context']['invest_money'] = StaticInstance::find()->where(['member_id' => $users, 'order_type' => [1, 2, 3]])->sum('in_num');
            }
        }
		//遍历规则
		$maxLevel = 0;
		$jsRate = 0;
		foreach(self::$conf as $val)
		{
			$ruleData['rule'] = $val['condition'];
			if(Validata::validata($ruleData)) $maxLevel = $val['level'];

			if($val['level'] == $level) $jsRate = $val['rate'];
		}

		return $maxLevel >= $level ? $jsRate : 0;
	}


}